import http3 from '@/utils/request3'
import layout from '@/components/layout/Body.vue'
import { getUserId } from '@/utils/cookies'
import { useMicro } from '@/hooks/useMicro'

const notFoundRouter = {
	path: '*',
	component: () => import('@/pages/NotFoundPage.vue'),
	hidden: true
}

const RouteView = {
	name: 'RouteView',
	render: h => h('router-view')
}

const rootRouter = {
	key: '',
	name: 'index',
	path: '/',
	component: layout,
	redirect: '/home',
	meta: {
		title: '首页'
	},
	children: []
}

export const generatorDynamicRouter = () => {
	const micro = useMicro()
	let userId = ''
	if (micro.isMicro) {
		const { user } = window.microApp.getData()
		userId = user.user_id
	}
	userId = getUserId() || userId
	return new Promise((resolve, reject) => {
		http3
			.get('/menu-perm/tree', {
				role__users: userId,
				menu__system: 'CICD'
			})
			.then(res => {
				if (res.code === 200) {
					const menuNav = []
					const routers = generator(res.data)
					rootRouter.children = routers
					menuNav.push(rootRouter)
					menuNav.push(notFoundRouter)
					resolve(menuNav)
				}
			})
			.catch(err => {
				reject(err)
			})
	})
}

export const generator = (routerMap, parent) => {
	return routerMap.map(item => {
		const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item || {}
		const currentRouter = {
			path: item.path || `${(parent && parent.path) || ''}/${item.key}`,
			name: item.name || item.key || '',
			component: item.component ? () => import(`@/pages/${item.component}.vue`) : RouteView,
			meta: {
				title: title,
				icon: icon || undefined,
				hiddenHeaderContent: hiddenHeaderContent,
				target,
				permission: item.name
			}
		}
		if (show === false) {
			currentRouter.hidden = true
		}
		if (hideChildren) {
			currentRouter.hideChildrenInMenu = true
		}
		if (!currentRouter.path.startsWith('http')) {
			currentRouter.path = currentRouter.path.replace('//', '/')
		}
		item.redirect && (currentRouter.redirect = item.redirect)
		if (item.children && item.children.length > 0) {
			currentRouter.children = generator(item.children, currentRouter)
		}
		return currentRouter
	})
}

const listToTree = (list, tree, parentId) => {
	list.forEach(item => {
		if (item.parentId === parentId) {
			const child = {
				...item,
				key: item.key || item.name,
				children: []
			}
			listToTree(list, child.children, item.id)
			if (child.children.length <= 0) {
				delete child.children
			}
			tree.push(child)
		}
	})
}
